package com.weather.androidweather.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LocationHelper {
    private static final String TAG = "LocationHelper";
    private static final int TIMEOUT = 10000; // 10秒超时
    private static final int MAX_RETRY_COUNT = 3; // 最大重试次数
    private static final int PERMISSION_REQUEST_CODE = 1001; // 权限请求码

    // 默认位置（北京）
    private static final double DEFAULT_LATITUDE = 39.9042;
    private static final double DEFAULT_LONGITUDE = 116.4074;
    private static final String DEFAULT_CITY = "北京";

    private Context context;
    private LocationClient locationClient;
    private LocationCallback callback;
    private Handler mainHandler;
    private boolean isLocationSuccess = false;
    private int retryCount = 0; // 当前重试次数
    private boolean isLocationing = false; // 是否正在定位中
    private GeocodingHelper geocodingHelper; // 地理编码助手
    private boolean isWaitingForPermission = false; // 是否正在等待权限

    public interface LocationCallback {
        void onSuccess(String city);
        void onFailed(String error);
        void onPermissionDenied(); // 权限被拒绝的回调
    }

    public LocationHelper(Context context) {
        // 使用ApplicationContext
        this.context = context.getApplicationContext();
        mainHandler = new Handler(Looper.getMainLooper());
        geocodingHelper = new GeocodingHelper(); // 初始化地理编码助手
        Log.d(TAG, "开始初始化定位服务");
        
        // 检查网络状态
        if (!NetworkUtils.isNetworkAvailable(this.context)) {
            Log.e(TAG, "网络不可用，定位服务初始化失败");
            return;
        }
        Log.d(TAG, "网络状态: " + (NetworkUtils.isNetworkAvailable(this.context) ? "已连接" : "未连接"));
        
        try {
            // 设置同意隐私政策 - 使用LocationClient.setAgreePrivacy
            LocationClient.setAgreePrivacy(true);
            Log.d(TAG, "已设置同意隐私政策");
            
            // 创建LocationClient实例
            locationClient = new LocationClient(this.context);
            Log.d(TAG, "创建LocationClient实例");
            
            // 设置定位参数
            LocationClientOption option = new LocationClientOption();
            // 设置定位模式为高精度模式
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
            // 设置坐标系类型为百度坐标系
            option.setCoorType("bd09ll");
            // 设置定位间隔，每5秒请求一次
            option.setScanSpan(5000);
            // 设置是否需要地址信息
            option.setIsNeedAddress(true);
            // 设置是否需要最新版本的地址信息
            option.setNeedNewVersionRgc(true);
            // 设置是否需要位置描述
            option.setIsNeedLocationDescribe(true);
            // 设置是否打开GPS
            option.setOpenGps(true);
//            // 启用Wi-Fi扫描
//            option.setWifiScan(true);
//            // 设置手机基站更新间隔
//            option.setCellUpdateInterval(5000);
            // 设置是否忽略进程被杀死的情况
            option.setIgnoreKillProcess(false);
            // 设置是否允许模拟位置
            option.setEnableSimulateGps(false);
            
            locationClient.setLocOption(option);
            Log.d(TAG, "定位参数设置完成");
            
            // 启动定位服务
            locationClient.start();
            Log.d(TAG, "启动定位服务");
        } catch (Exception e) {
            Log.e(TAG, "定位服务初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 检查是否有定位权限
    public boolean checkLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查精确位置权限
            boolean hasFineLocation = ContextCompat.checkSelfPermission(context, 
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            // 检查粗略位置权限
            boolean hasCoarseLocation = ContextCompat.checkSelfPermission(context, 
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            
            Log.d(TAG, "精确位置权限: " + (hasFineLocation ? "已授权" : "未授权"));
            Log.d(TAG, "粗略位置权限: " + (hasCoarseLocation ? "已授权" : "未授权"));
            
            return hasFineLocation && hasCoarseLocation;
        }
        return true; // 低于Android 6.0的版本不需要动态申请权限
    }

    // 申请定位权限
    public void requestLocationPermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!checkLocationPermission()) {
                Log.d(TAG, "开始申请定位权限");
                isWaitingForPermission = true;
                ActivityCompat.requestPermissions(activity, 
                        new String[]{
                                Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION
                        }, 
                        PERMISSION_REQUEST_CODE);
            } else {
                Log.d(TAG, "已有定位权限，无需申请");
            }
        }
    }

    // 处理权限申请结果
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            isWaitingForPermission = false;
            boolean allGranted = true;
            
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            
            if (allGranted) {
                Log.d(TAG, "用户已授予所有定位权限");
                // 如果正在等待权限，则继续定位
                if (callback != null && isLocationing) {
                    startLocation(callback);
                }
            } else {
                Log.e(TAG, "用户拒绝了定位权限");
                if (callback != null) {
                    callback.onPermissionDenied();
                }
            }
        }
    }

    public void startLocation(final LocationCallback callback) {
        // 如果已经在定位中，则不再重复启动定位
        if (isLocationing) {
            Log.d(TAG, "已经在定位中，不再重复启动定位");
            return;
        }
        
        // 检查权限
        if (!checkLocationPermission()) {
            Log.e(TAG, "没有定位权限，无法开始定位");
            if (callback != null) {
                callback.onPermissionDenied();
            }
            return;
        }
        
        Log.d(TAG, "开始定位流程");
        this.callback = callback;
        retryCount = 0; // 重置重试次数
        isLocationSuccess = false; // 重置定位成功标志
        isLocationing = true; // 标记正在定位中
        
        if (locationClient == null) {
            Log.e(TAG, "LocationClient未初始化");
            isLocationing = false; // 重置定位状态
            if (callback != null) {
                callback.onFailed("定位服务未初始化");
            }
            return;
        }
        
        if (!locationClient.isStarted()) {
            Log.d(TAG, "启动定位服务");
            locationClient.start();
        }
        
        locationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                Log.d(TAG, "定位类型: " + location.getLocType());
                Log.d(TAG, "定位结果: " + location.getAddrStr());
                Log.d(TAG, "纬度: " + location.getLatitude());
                Log.d(TAG, "经度: " + location.getLongitude());
                Log.d(TAG, "精度: " + location.getRadius());
                Log.d(TAG, "定位时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                
                if (location.getLocType() == BDLocation.TypeGpsLocation || 
                    location.getLocType() == BDLocation.TypeNetWorkLocation ||
                    location.getLocType() == BDLocation.TypeOffLineLocation) {
                    
                    // 使用GeocodingHelper获取城市名
                    geocodingHelper.getCityFromLocation(location.getLatitude(), location.getLongitude(), new GeocodingHelper.GeocodingCallback() {
                        @Override
                        public void onSuccess(String city) {
                            isLocationSuccess = true; // 标记定位成功
                            isLocationing = false; // 重置定位状态
                            if (callback != null) {
                                callback.onSuccess(city);
                            }
                            stopLocation(); // 定位成功后停止定位
                        }
                        
                        @Override
                        public void onFailed(String error) {
                            handleLocationFailed("获取城市名失败: " + error);
                        }
                    });
                } else {
                    handleLocationFailed("定位失败，错误码: " + location.getLocType());
                }
            }
        });
        
        // 启动超时计时器
        startTimeoutTimer();
    }

    private void startTimeoutTimer() {
        mainHandler.postDelayed(() -> {
            if (!isLocationSuccess && isLocationing) {
                handleLocationFailed("定位超时，请检查网络连接和GPS设置");
            }
        }, TIMEOUT);
    }

    private void handleLocationSuccess(String city) {
        mainHandler.post(() -> {
            isLocationing = false; // 重置定位状态
            if (callback != null) {
                callback.onSuccess(city);
            }
            stopLocation();
        });
    }

    private void handleLocationFailed(String error) {
        mainHandler.post(() -> {
            if (retryCount < MAX_RETRY_COUNT) {
                retryCount++;
                Log.w(TAG, "定位失败，正在进行第 " + retryCount + " 次重试");
                // 延迟1秒后重试
                mainHandler.postDelayed(() -> {
                    if (locationClient != null && !isLocationSuccess && isLocationing) {
                        startLocation(callback);
                    }
                }, 1000);
            } else {
                Log.e(TAG, "定位失败，已达到最大重试次数: " + MAX_RETRY_COUNT);
                isLocationing = false; // 重置定位状态
                if (callback != null) {
                    // 使用默认位置
                    Log.d(TAG, "使用默认位置: " + DEFAULT_CITY);
                    callback.onSuccess(DEFAULT_CITY);
                }
                stopLocation();
            }
        });
    }

    public void stopLocation() {
        isLocationing = false; // 重置定位状态
        if (locationClient != null) {
            try {
                locationClient.stop();
            } catch (Exception e) {
                Log.e(TAG, "停止定位失败", e);
            }
        }
    }

    public void destroy() {
        stopLocation();
        if (locationClient != null) {
            try {
                locationClient = null;
            } catch (Exception e) {
                Log.e(TAG, "销毁定位服务失败", e);
            }
        }
    }
} 